package com.rjt.qrcode.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rjt.permission.Permission;
import com.rjt.qrcode.model.QrCodeModel;
import com.rjt.qrcode.service.QrCodeService;
import com.rjt.qrcode.service.QrCodeVisitService;
import com.rjt.qrcode.vo.QrCodeVisitVo;

@Controller
@RequestMapping("qrCode")
public class QrCodeController {
	
	@Autowired
	private QrCodeService qrCodeService;
	
	@Autowired
	private QrCodeVisitService qrCodeVisitService;
	
	@GetMapping("qrCodeList")
	@ResponseBody
	@Permission
	public Page<QrCodeModel>  qrCodeList(HttpServletRequest request){
		
		return qrCodeService.getList(request);
	}
	
	@GetMapping("list")
	@Permission
	public String list() {
		return "qrCode/list";
	}
	
	@GetMapping("{id}")
	public String index(@PathVariable(value="id") String id,HttpServletRequest request) {
		 QrCodeModel qrCode = qrCodeService.findQrCode(id);
		 if(qrCode==null) {
				return "common/error";
		 }
		 qrCodeVisitService.save(id, request);
		 return "redirect:" + qrCode.getContent();
	}
	
	
	@ResponseBody
	@PostMapping("delQrCode")
	@Permission
	public String delQrCodeModel(@RequestBody List<QrCodeModel> qrCode) {
		return qrCodeService.delete(qrCode);
	}
	
	@GetMapping("toUpdatePage")
	public String toUpdatePage(String id,HttpServletRequest request) {
		QrCodeModel qrCode = qrCodeService.findQrCode(id);
		request.setAttribute("qrCode",qrCode);
		return "qrCode/edit";
	}
	
	@PostMapping("editQrCode")
	@ResponseBody
	@Permission
	public String editQrCodeModel(@RequestBody QrCodeModel qrCode) {
		return qrCodeService.add(qrCode,"edit");
	}
	
	@GetMapping("toNewPage")
	public String toNewPage() {
		return "qrCode/add";
	}
	
	@PostMapping("addQrCode")
	@ResponseBody
	@Permission
	public String addArticle(@RequestBody QrCodeModel qrCode) {
		return qrCodeService.add(qrCode,"save");
	}
	
	@GetMapping("toCountPage")
	public String toCountPage(String id,HttpServletRequest req) {
		req.setAttribute("qId", id);
		return "qrCode/count";
	}
	
	@GetMapping("countByArea")
	@ResponseBody
	@Permission
	public List<QrCodeVisitVo> countByArea(String rId) {
		return qrCodeVisitService.countByRIdAndArea(rId);
	}
	
	@GetMapping("countByDate")
	@ResponseBody
	@Permission
	public List<QrCodeVisitVo> countByDate(String rId) {
		return qrCodeVisitService.countByRIdAndDate(rId);
	}
}
